import java.net.*;
import java.util.Hashtable;
import java.util.Map;
import java.io.*;

import org.apache.commons.codec.binary.Base64;

public class SimpleClient {

	public class HttpParser {
		private BufferedReader reader;
		private String initial;
		private Hashtable<String, String> headers;

		public HttpParser(InputStream is) {
			reader = new BufferedReader(new InputStreamReader(is));
			headers = new Hashtable<String, String>();
		}

		public int parseResponse() throws IOException {
			initial = reader.readLine();
			int statuscode = Integer.parseInt(initial.substring(9, 12)); // not_pretty_code.com ;)
			parseHeaders();
			return statuscode;
		}

		private void parseHeaders() throws IOException {
			String line;
			int idx;
			line = reader.readLine();
			while (!line.equals("")) {
				idx = line.indexOf(':');
				if (idx < 0) {
					headers = null;
					break;
				} else {
					headers.put(line.substring(0, idx).toLowerCase(), line
							.substring(idx + 1).trim());
				}
				line = reader.readLine();
			}
		}

		public String getHeader(String key) {
			if (headers != null)
				return (String) headers.get(key.toLowerCase());
			else
				return null;
		}

		public Hashtable<String, String> getHeaders() {
			return headers;
		}

		public String fullHeader() {
			StringBuilder header = new StringBuilder();
			header.append(initial + "\n");
			for (Map.Entry<String, String> entry : headers.entrySet()) {
				header.append(entry.getKey() + " = " + entry.getValue() + "\n");
			}
			return header.toString();
		}

		public String rawBody() {
			return ""; // todo
		}
	}
	
	public void doGet(String host, int port, String path,
			boolean doAuthentication, String username, String password) {
		try {
			Socket connection = new Socket(host, port);
			BufferedWriter output = new BufferedWriter(new OutputStreamWriter(
					connection.getOutputStream(), "UTF8"));
			output.write("GET /" + path + " HTTP/1.1\r\n");
			output.write("Host: " + host + "\r\n");

			if (doAuthentication) {
				output.write("Authorization: Basic "
						+ Base64.encodeBase64(
								String.format("%s:%s", username, password)
										.getBytes()).toString() + "\r\n");
			}
			output.write("\r\n");
			output.flush();

			HttpParser parser = new HttpParser(connection.getInputStream());

			int value = parser.parseResponse();
			System.out.println("full: " + parser.fullHeader());
			switch (value) {
			case 301:
				String location = parser.getHeader("location").substring(7, 13);
				System.out.println("Do redirect to : " + location);
				doGet(location, port, path, doAuthentication, username, password);
				break;
			default:
				System.out.println("Value : " + value);
			}
			connection.close();
		} catch (Exception e) {
			System.out.println("error: " + e.getMessage());
		}
	}

	public static void main(String[] args) {
		System.out.println("start");
		SimpleClient c = new SimpleClient();
		c.doGet("www.tv2.dk", 80, "", false, "", "");
		System.out.println("end");
	}
}
